package cosplay.servlet;
import java.io.IOException;
import cosplay.DAO.PhotoDAOImpl;
import cosplay.DAO.UserDAOImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class Jpgservlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4694869124093901168L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		UserDAOImpl userdao=(UserDAOImpl) context.getAutowireCapableBeanFactory().createBean(cosplay.DAO.UserDAOImpl.class);
		PhotoDAOImpl photodao=(PhotoDAOImpl) context.getAutowireCapableBeanFactory().createBean(cosplay.DAO.PhotoDAOImpl.class);
		String name=req.getRequestURI();
		name=name.substring(name.lastIndexOf("/")+1);
		name=name.replaceAll(".jpg", "");
		byte[] jpg =null;
		if (name.startsWith("preview_"))
		{
			name=name.replaceAll("preview_", "");
			if (cosplay.Services.FileServices.Stringintcheck(name))
				jpg=photodao.getPreview(Integer.valueOf(name).intValue());
		}
		if (name.startsWith("photo_"))
		{
			name=name.replaceAll("photo_", "");
			if (cosplay.Services.FileServices.Stringintcheck(name))
			{
				jpg=photodao.getImage(Integer.valueOf(name).intValue());
			}
		}
		if (name.startsWith("head_"))
		{
			name=name.replaceAll("head_", "");
			if (cosplay.Services.FileServices.Stringintcheck(name))
				jpg=userdao.getHeadImage(Integer.valueOf(name).intValue());
		}
		if (jpg!=null)
			resp.getOutputStream().write(jpg);
		else
			resp.getOutputStream().println("photo not found");
	}
}
